<template>
  <div class="app-container">
    <!-- 搜索表单部分保持不变 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">

      <!-- 在原有搜索表单内添加 -->
      <el-form-item label="家庭" prop="familyId" style="width: 200px;">
        <el-select
            v-model="queryParams.familyId"
            placeholder="选择家庭"
            clearable
            @change="handleFamilyFilter"
        >
          <el-option
              v-for="item in familyOptions"
              :key="item.familyId"
              :label="item.familyName"
              :value="item.familyId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="房间" prop="roomId" style="width: 200px;">
        <el-select
            v-model="queryParams.roomId"
            placeholder="先选择家庭"
            clearable
            :disabled="!queryParams.familyId"
            @change="handleQuery"
        >
          <el-option
              v-for="item in filteredSearchRooms"
              :key="item.roomId"
              :label="item.roomName"
              :value="item.roomId"
          />
        </el-select>
      </el-form-item>


<!--      <el-form-item label="设备ID" prop="deviceId" style="width: 350px;">-->
<!--        <el-select-->
<!--            v-model="queryParams.deviceId"-->
<!--            placeholder="请选择设备"-->
<!--            clearable-->
<!--            filterable-->
<!--            @keyup.enter="handleQuery"-->
<!--        >-->
<!--          <el-option-->
<!--              v-for="item in deviceOptions"-->
<!--              :key="item.deviceId"-->
<!--              :label="`设备ID:${item.deviceId}`"-->
<!--              :value="item.deviceId"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="警告时间" prop="warningTime">
        <el-date-picker clearable
                        v-model="queryParams.warningTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择警告时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮部分保持不变 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['airsystem:warnings:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['airsystem:warnings:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['airsystem:warnings:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['airsystem:warnings:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格部分 - 只显示设备ID在下拉框中的警告记录 -->
    <el-table v-loading="loading" :data="filteredWarningsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="警告ID" align="center" prop="warningId" />-->
      <el-table-column
          label="序号"
          align="center"
          width="80"
          class-name="serial-number"
      >
        <template #default="scope">
    <span class="serial">
      {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
    </span>
        </template>
      </el-table-column>


      <el-table-column label="家庭名称" align="center">
        <template #default="scope">
          {{ getFamilyName(scope.row.deviceId) }}
        </template>
      </el-table-column>

      <el-table-column label="房间名称" align="center">
        <template #default="scope">
          {{ getRoomName(scope.row.deviceId) }}
        </template>
      </el-table-column>


<!--      <el-table-column label="设备ID" align="center">-->
<!--        <template #default="scope">-->
<!--          设备ID:{{ scope.row.deviceId }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="警告信息" align="center" prop="warningMessage" />
      <el-table-column label="警告时间" align="center" prop="warningTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.warningTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['airsystem:warnings:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['airsystem:warnings:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页部分保持不变 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 对话框部分保持不变 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="warningsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备ID" prop="deviceId">
          <el-select
              v-model="form.deviceId"
              placeholder="请选择设备"
              clearable
              filterable
          >
            <el-option
                v-for="item in deviceOptions"
                :key="item.deviceId"
                :label="`设备ID:${item.deviceId}`"
                :value="item.deviceId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="警告信息" prop="warningMessage">
          <el-input v-model="form.warningMessage" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="警告时间" prop="warningTime">
          <el-date-picker clearable
                          v-model="form.warningTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择警告时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Warnings">
import {listWarnings, getWarnings, delWarnings, addWarnings, updateWarnings} from "@/api/airsystem/warnings";
import {listDevices} from "@/api/airsystem/devices";
import {ref, reactive, getCurrentInstance, onMounted, computed} from 'vue';
import { listRooms } from "@/api/airsystem/rooms";
import { listFamilies } from "@/api/airsystem/families";
const {proxy} = getCurrentInstance();

const warningsList = ref([]);
const deviceOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 在现有响应式数据后添加
const roomOptions = ref([]);
const familyOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    familyId: null,
    roomId: null,
    deviceId: null,
    warningMessage: null,
    warningTime: null
  },
  rules: {
    deviceId: [
      {required: true, message: "设备ID不能为空", trigger: "blur"}
    ],
    warningMessage: [
      {required: true, message: "警告信息不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

// 只显示设备ID存在于deviceOptions中的警告记录
// const filteredWarningsList = computed(() => {
//   const deviceIds = deviceOptions.value.map(item => item.deviceId);
//   return warningsList.value.filter(item => deviceIds.includes(item.deviceId));
// });
// 修改filteredWarningsList计算属性
const filteredWarningsList = computed(() => {
  return warningsList.value.filter(item => {
    const device = deviceOptions.value.find(d => d.deviceId === item.deviceId);
    if (!device) return false;

    // 家庭过滤
    const familyMatch = queryParams.value.familyId
        ? roomOptions.value.find(r => r.roomId === device.roomId)?.familyId === queryParams.value.familyId
        : true;

    // 房间过滤
    const roomMatch = queryParams.value.roomId
        ? device.roomId === queryParams.value.roomId
        : true;

    return familyMatch && roomMatch;
  }).map(item => ({
    ...item,
    _familyName: getFamilyName(item.deviceId),
    _roomName: getRoomName(item.deviceId)
  }));
});


// 在现有方法后添加
const getDeviceInfo = (deviceId) => {
  return deviceOptions.value.find(d => d.deviceId === deviceId);
};

const getRoomName = (deviceId) => {
  const device = getDeviceInfo(deviceId);
  if (!device) return '未知设备';
  const room = roomOptions.value.find(r => r.roomId === device.roomId);
  return room?.roomName || '未知房间';
};

const getFamilyName = (deviceId) => {
  const device = getDeviceInfo(deviceId);
  if (!device) return '未知设备';
  const room = roomOptions.value.find(r => r.roomId === device.roomId);
  if (!room) return '未知房间';
  const family = familyOptions.value.find(f => f.familyId === room.familyId);
  return family?.familyName || '未知家庭';
};
// 添加过滤后的房间列表
const filteredSearchRooms = computed(() => {
  return roomOptions.value.filter(room =>
      room.familyId === queryParams.value.familyId
  );
});
// 添加家庭选择处理
const handleFamilyFilter = () => {
  queryParams.value.roomId = null; // 清空房间选择
  queryParams.value.deviceId = null; // 清空设备选择
  handleQuery(); // 触发搜索
};

/** 获取所有设备 */
async function getAllDevices() {
  try {
    const response = await listDevices({
      pageNum: 1,
      pageSize: 1000
    });
    return response.rows || [];
  } catch (error) {
    console.error("获取设备失败:", error);
    proxy.$modal.msgError("获取设备数据失败");
    return [];
  }
}

/** 查询设备列表 */
async function getDeviceList() {
  loading.value = true;
  try {
    deviceOptions.value = await getAllDevices();
    if (deviceOptions.value.length === 0) {
      proxy.$modal.msgWarning("系统中未找到设备");
    }
  } catch (error) {
    console.error("处理设备数据失败:", error);
    proxy.$modal.msgError("获取设备失败");
  } finally {
    loading.value = false;
  }
}

/** 查询警告管理列表 */
async function getList() {
  loading.value = true;
  try {
    const response = await listWarnings(queryParams.value);
    warningsList.value = response.rows || [];
    total.value = response.total || 0;
  } catch (error) {
    console.error("获取警告列表失败:", error);
    proxy.$modal.msgError("获取警告列表失败");
  } finally {
    loading.value = false;
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    warningId: null,
    deviceId: null,
    warningMessage: null,
    warningTime: null
  };
  proxy.resetForm("warningsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    familyId: null,  // 新增
    roomId: null,    // 新增
    deviceId: null,
    warningMessage: null,
    warningTime: null
  };
  handleQuery();
}



// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.warningId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加警告管理";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const _warningId = row.warningId || ids.value;
  try {
    const response = await getWarnings(_warningId);
    form.value = response.data;
    open.value = true;
    title.value = "修改警告管理";
  } catch (error) {
    console.error("获取警告详情失败:", error);
    proxy.$modal.msgError("获取警告详情失败");
  }
}

/** 提交按钮 */
async function submitForm() {
  try {
    const valid = await proxy.$refs["warningsRef"].validate();
    if (!valid) return;

    // 验证设备ID是否存在
    const deviceExists = deviceOptions.value.some(d => d.deviceId === form.value.deviceId);
    if (!deviceExists) {
      proxy.$modal.msgError("选择的设备不存在");
      return;
    }

    if (form.value.warningId != null) {
      await updateWarnings(form.value);
      proxy.$modal.msgSuccess("修改成功");
    } else {
      await addWarnings(form.value);
      proxy.$modal.msgSuccess("新增成功");
    }
    open.value = false;
    getList();
  } catch (error) {
    console.error("提交表单失败:", error);
  }
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    const _warningIds = row.warningId || ids.value;
    await proxy.$modal.confirm(`是否确认删除警告管理编号为"${_warningIds}"的数据？`);
    await delWarnings(_warningIds);
    getList();
    proxy.$modal.msgSuccess("删除成功");
  } catch (error) {
    console.error("删除失败:", error);
  }
}

/** 导出按钮操作 */
function handleExport() {
  // 导出时也过滤只导出匹配的记录
  const deviceIds = deviceOptions.value.map(item => item.deviceId);
  const exportData = warningsList.value.filter(item => deviceIds.includes(item.deviceId));

  proxy.download('airsystem/warnings/export', {
    ...queryParams.value,
    deviceIds: deviceIds.join(',') // 传递设备ID过滤条件
  }, `warnings_${new Date().getTime()}.xlsx`)
}


// 在现有方法后添加这些方法
// 分页获取所有房间
async function getAllRooms() {
  let allRooms = [];
  let pageNum = 1;
  const pageSize = 100;

  try {
    while (true) {
      const response = await listRooms({ pageNum, pageSize });
      if (!response.rows?.length) break;
      allRooms = [...allRooms, ...response.rows];
      if (response.rows.length < pageSize) break;
      pageNum++;
    }
    return allRooms;
  } catch (error) {
    console.error("获取房间失败:", error);
    return [];
  }
}

// 分页获取所有家庭
async function getAllFamilies() {
  let allFamilies = [];
  let pageNum = 1;
  const pageSize = 100;

  try {
    while (true) {
      const response = await listFamilies({ pageNum, pageSize });
      if (!response.rows?.length) break;
      allFamilies = [...allFamilies, ...response.rows];
      if (response.rows.length < pageSize) break;
      pageNum++;
    }
    return allFamilies;
  } catch (error) {
    console.error("获取家庭失败:", error);
    return [];
  }
}


// 组件挂载时初始化
onMounted(async () => {
  await Promise.all([
    getDeviceList(),
    getAllRooms().then(rooms => roomOptions.value = rooms),
    getAllFamilies().then(families => familyOptions.value = families)
  ]);
  getList();
});



</script>
